package com.greatwall.hip.cms.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author TianLei
 * @version V1.0
 */
public class JWTRealm extends AuthorizingRealm {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JWTShiroService jwtShiroService;

    @Autowired
    private JWTProperties jwtProperties;

    public JWTRealm() {}

    @Override
    public boolean supports(AuthenticationToken token) {
        // 仅支持 JwtToken
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取用户名, 用户唯一标识
        String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 设置角色

        // 设置权限

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String loginName = (String) token.getPrincipal();
        String jwt = (String) token.getCredentials();
        Algorithm algorithm = Algorithm.HMAC256(jwtProperties.getSecretKey());
        JWTVerifier verifier = JWT.require(algorithm).build();
        try {
            verifier.verify(jwt);
            if(logger.isDebugEnabled()) {
                logger.debug("********************* TOKEN验证通过 ***********************");
            }
        } catch (JWTVerificationException e) {
            if(logger.isDebugEnabled()) {
                logger.debug("********************* TOKEN验证不通过 **********************");
            }
            throw new AuthenticationException("无效的用户TOKEN");
        }
        return new SimpleAuthenticationInfo(loginName, jwt, getName());
    }
}
